package com.sigmazero13.bgjeeves;

import java.util.Comparator;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.sigmazero13.bgjeeves.model.GamePlayInfo;
import com.sigmazero13.bgjeeves.utils.PlayListAdapter;

public class PlayList extends ListActivity {
	private int gameId = 0;
	private PlayListAdapter adapter;
	private List<GamePlayInfo> plays;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.play_list);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) gameId = bundle.getInt("game_id", 0);
		
		ListView lv = getListView();
		
		plays = ((BoardGameUtilsApp)getApplication()).getDbHelper().getPlaysForGame(gameId, true);
		
		adapter = new PlayListAdapter(this, R.layout.play_list_item, plays, gameId==0);
		this.setListAdapter(adapter);
		
		lv.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    			GamePlayInfo thisPlay = (GamePlayInfo)parent.getItemAtPosition(position);
    			Intent i = new Intent(PlayList.this, PlayInfoView.class);
    			i.putExtra("play_id", thisPlay.getPlayId());
    			startActivityForResult(i,0);
    		}
    	});
	}
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        if (resultCode == RESULT_OK) {
        	if (intent.getExtras() == null) return;
	        long playId = intent.getLongExtra("play_id", 0);
	        GamePlayInfo newPlay = ((BoardGameUtilsApp)getApplication()).getDbHelper().selectSinglePlay(playId);
	        GamePlayInfo oldPlay = null;
	        for (GamePlayInfo play : plays) {
	        	if (play.getPlayId() == playId) {
	        		oldPlay = play;
	        		break;
	        	}
	        }
	        
	        if (oldPlay != null) {
        		adapter.remove(oldPlay);
        		adapter.add(newPlay);
        		adapter.sort(new Comparator<GamePlayInfo>() {
					@Override
					public int compare(GamePlayInfo object1, GamePlayInfo object2) {
						return -object1.compareTo(object2);
					}
        		});
        	}
	        
	        adapter.notifyDataSetChanged();
        }
	}
}
